package com.bucks.services;

import com.bucks.bean.Coffee;
import com.bucks.bean.CoffeeOrder;
import com.bucks.bean.OrderState;
import com.bucks.repository.CoffeeOrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Arrays;

/**

 * @date 2019-11-12
 */
@Slf4j
@Service
@Transactional
public class CoffeeOrderService {
    @Autowired
    private CoffeeOrderRepository coffeeOrderRepository;

    public CoffeeOrder createOrder(String customer, Coffee...coffees){
        CoffeeOrder order = CoffeeOrder.builder()
                .customer(customer)
                .items(Arrays.asList(coffees))
                .state(OrderState.INIT)
                .build();
        CoffeeOrder saved = coffeeOrderRepository.save(order);
        log.info("New Order: {} ", saved);
        log.info("New Order: {} ", order);
        return saved;
    }

    public boolean updateState(CoffeeOrder order,OrderState state){
        if (state.compareTo(order.getState())<=0){
            log.warn("Wrong State order: {} ",state , order.getState());
            return false;
        }
        order.setState(state);
        coffeeOrderRepository.save(order);
        log.info("Updated Order: {} ",order);
        return true;
    }
}
